<template>
  <el-dialog v-model="isDialogShow" title="修改日历" width="500" @closed="handleDialogClosed">
    <el-form ref="formRef" :model="form">
      <el-form-item label="是否休息" prop="is_rest">
        <el-switch v-model="form.is_rest" :active-value="1" :inactive-value="0"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        <el-button @click="handleCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ref} from "vue";
import {ElForm, ElMessage} from "element-plus";
import {updateSystemDate} from "@/api/systemDate";
import {isAxiosError} from "axios";

const emit = defineEmits<{
  success: []
  updateSuccess: []
}>()
const form = defineModel<SystemDateRequest>({default: {}})
const formRef = ref<InstanceType<typeof ElForm>>()
const isDialogShow = defineModel<boolean>("show")

function handleCancelClick() {
  isDialogShow.value = false
}

function handleConfirmClick() {
  formRef.value?.validate(async (isValid) => {
    if (isValid) {
      try {
        const {code, msg} = await updateSystemDate(form.value)
        if (code === "200") {
          ElMessage.success(msg);
          emit("updateSuccess")
          emit("success")
        } else {
          ElMessage.error(msg)
        }
        isDialogShow.value = false;
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  })
}

async function handleDialogClosed() {
  formRef.value?.resetFields()
}
</script>
